package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vos.ApUserVO;
import com.heima.model.user.vos.LoginVO;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

/**
 * @Author XHui
 * @Since 2024/2/17 10:52
 * @Version 1.0
 */
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Resource
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        // 1. 判断手机号 和 密码 是否为空
        if (StringUtils.isNotBlank(dto.getPhone()) &&
                StringUtils.isNotBlank(dto.getPassword())) {
            ApUser apUser = apUserMapper.selectOne(
                    Wrappers.<ApUser>lambdaQuery()
                            .eq(ApUser::getPhone, dto.getPhone()));
            // 1.1 若不为空，查询手机号对应的用户是否存在
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
            // 1.2 对比输入的密码 和 数据库中的密码是否一致
            String password = apUser.getPassword();
            String salt = apUser.getSalt();
            String encryptedPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            if (!password.equals(encryptedPassword)) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户不存在或密码错误");
            }
            // 1.3 颁发token,并返回user token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            LoginVO loginVO = new LoginVO();
            loginVO.setToken(token);

            ApUserVO apUserVO = new ApUserVO();
            BeanUtils.copyProperties(apUser, apUserVO);
            loginVO.setApUserVO(apUserVO);
            return ResponseResult.okResult(loginVO);
        } else {
            // 2. 若手机号和密码为空，采用设备唯一id作为登录
            // 2.1 判断设备id是否存在
            if(dto.getEquipmentId() == null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "设备id不能为空");
            }
            // 2.2 直接颁发token，userId存储0
            String token = AppJwtUtil.getToken(0L);
            LoginVO loginVO = new LoginVO();
            loginVO.setToken(token);
            return ResponseResult.okResult(loginVO);
        }

    }
}
